package linker;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import data.SimpleStatement;
import data.SimpleURI;
import data.Statement;

public class Parser {
	private InputStreamReader reader;
	private Statement next;
	private String charsetName;

	public Parser(Properties config) {
		if (config != null) {
			charsetName = config.getProperty("charset");
		}
		charsetName = null;
	}

	public void open(String path) throws FileNotFoundException,
			UnsupportedEncodingException {

		FileInputStream inFile = new FileInputStream(path);
		if (charsetName != null)
			reader = new InputStreamReader(inFile, "UTF8");
		else
			reader = new InputStreamReader(inFile);
	}

	public void close() throws IOException {
		if (reader != null)
			reader.close();
	}

	public boolean hasNext() {
		if (next != null)
			return true;
		else {
			try {
				next = parseNext();
				if (next != null)
					return true;
				else
					return false;
			} catch (IOException e) {
				next = null;
				return false;
			}

		}
	}

	public Statement nextStatement() {
		if (next != null) {
			Statement ret = next;
			next = null;
			return ret;
		}
		try {
			return parseNext();
		} catch (IOException e) {
			return null;
		}

	}

	private Statement parseNext() throws IOException {

		StringBuffer subject = new StringBuffer();
		StringBuffer object = new StringBuffer();
		StringBuffer predicate = new StringBuffer();

		// get first <>
		int c;
		while ((c = reader.read()) != '<') {
			if (c == -1)
				return null;
		}
		while ((c = reader.read()) != '>') {
			if (c == -1)
				return null;
			else
				subject.append((char)c);
		}

		// get second <>

		while ((c = reader.read()) != '<') {
			if (c == -1)
				return null;
		}
		while ((c = reader.read()) != '>') {
			if (c == -1)
				return null;
			else
				predicate.append((char)c);
		}

		// get third <>

		while ((c = reader.read()) != '<') {
			if (c == -1)
				return null;
		}
		while ((c = reader.read()) != '>') {
			if (c == -1)
				return null;
			else
				object.append((char)c);
		}

		SimpleURI sub= new SimpleURI(subject.toString().split("#")[0],subject.toString().split("#")[1]);
		SimpleURI obj= new SimpleURI(object.toString().split("#")[0],object.toString().split("#")[1]);
		SimpleURI pred= new SimpleURI(predicate.toString().split("#")[0],predicate.toString().split("#")[1]);

		SimpleStatement ret = new SimpleStatement(sub, pred, obj);
		return ret;

	}
}
